package cn.wizzer.app.chain.modules.controller;


import cn.wizzer.app.chain.modules.models.T_copyright;
import cn.wizzer.app.chain.modules.services.TCopyrightService;
import cn.wizzer.app.sys.modules.models.Sys_config;
import cn.wizzer.app.sys.modules.services.SysConfigService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.page.datatable.DataTableColumn;
import cn.wizzer.framework.page.datatable.DataTableOrder;
import cn.wizzer.framework.util.MoacUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.adaptor.WhaleAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@IocBean
@At("/chain/copyright")
public class TCopyrightController {
	private static final Log log = Logs.get();
	@Inject
	private TCopyrightService tCopyrightService;

	@Inject
	private SysConfigService configService;

	@At("")
	@Ok("beetl:/chain/copyright/index.html")
	@RequiresAuthentication
	public void index() {

	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		Cnd cnd = Cnd.NEW();
    	return tCopyrightService.data(length, start, draw, order, columns, cnd, null);
    }

    @At
    @Ok("beetl:/chain/copyright/add.html")
    @RequiresAuthentication
    public void add() {

    }

    @At
    @Ok("json")
    @SLog(tag = "新建版权", msg = "")
	@AdaptBy(type = WhaleAdaptor.class)
    public Object addDo(@Param("..") T_copyright tCopyright, HttpServletRequest req) {
		try {
			tCopyright.setRegisterTime(new Date());
			tCopyrightService.insert(tCopyright);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }

    @At("/edit/?")
    @Ok("beetl:/chain/copyright/edit.html")
    @RequiresAuthentication
    public Object edit(String id) {
		return tCopyrightService.fetch(id);
    }

    @At
    @Ok("json")
    @SLog(tag = "修改版权", msg = "ID:${args[0].id}")
    public Object editDo(@Param("..") T_copyright tCopyright, HttpServletRequest req) {
		try {

			tCopyright.setOpAt((int) (System.currentTimeMillis() / 1000));
			tCopyrightService.updateIgnoreNull(tCopyright);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }


    @At({"/delete","/delete/?"})
    @Ok("json")
    @SLog(tag = "删除版权", msg = "ID:${args[2].getAttribute('id')}")
    public Object delete(String id, @Param("ids") String[] ids ,HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				tCopyrightService.delete(ids);
    			req.setAttribute("id", org.apache.shiro.util.StringUtils.toString(ids));
			}else{
				tCopyrightService.delete(id);
    			req.setAttribute("id", id);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }


    @At("/detail/?")
    @Ok("beetl:/chain/copyright/detail.html")
    @RequiresAuthentication
	public Object detail(String id) {
		if (!Strings.isBlank(id)) {
			return tCopyrightService.fetch(id);
		}
		return null;
    }

    @At("/addChain")
	public Object addChain(String copyRightId) throws Exception{
        //获取ip
		Sys_config chainIp_conf =configService.fetch("chain_ip");
		String chain_url=chainIp_conf.getConfigValue();
		//获取keystorefile
		Sys_config keystorefile_conf =configService.fetch("keystorefile");
		String keystorefile=keystorefile_conf.getConfigValue();
		//获取chain:pwd
        Sys_config chainPwd_conf =configService.fetch("chain_pwd");
		String pwd=chainPwd_conf.getConfigValue();
		//获取publicKey
		Sys_config publicKey_conf =configService.fetch("publickey");
        String publicKey=publicKey_conf.getConfigValue();

		T_copyright copyright;
        if (!Strings.isBlank(copyRightId)) {
		    copyright = tCopyrightService.fetch(copyRightId);
		}else{
        	return Result.error("system.error");
		}
		        MoacUtil moacUtil = new MoacUtil(
                "http://127.0.0.1:8545",
                "C:\\Users\\Administrator\\AppData\\Roaming\\MoacNode\\devnet\\keystore\\UTC--2018-12-19T02-32-35.977436900Z--7d0bc69501aca899e3eb0d7b08982af9aa21b543",
                "123456",
                "0xb01ff7f6e31602534017311470c5d5c0a6b8a400");
		//MoacUtil moacUtil = new MoacUtil(chain_url,keystorefile,pwd,publicKey);
       //上链
       String hash = moacUtil.sendTransaction("hello word");
       if(hash!=null){
         	copyright.setBlockChainTransactionCode(hash);
         	this.tCopyrightService.updateIgnoreNull(copyright);
         	return Result.success("addChain success");
	     }else {
          	return Result.error("addChain error");
	     }
    }
}
